#!/bin/bash

echo "=== 语音录制服务状态检查 ==="
echo "检查时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# 检查Gunicorn进程
echo "1. Gunicorn进程状态:"
if pgrep -f gunicorn > /dev/null; then
    echo "   ✅ Gunicorn进程正在运行"
    echo "   进程详情:"
    pgrep -af gunicorn | sed 's/^/   /'
    
    # 检查worker数量
    WORKER_COUNT=$(pgrep -f "gunicorn: worker" | wc -l)
    echo "   当前worker数量: $WORKER_COUNT"
else
    echo "   ❌ 没有发现运行中的Gunicorn进程"
fi

echo ""
# 检查端口占用
echo "2. 端口状态:"
if netstat -tulpn 2>/dev/null | grep -q ":8000 "; then
    echo "   ✅ 端口8000正在监听"
    netstat -tulpn 2>/dev/null | grep ":8000 " | sed 's/^/   /'
else
    echo "   ❌ 端口8000未被监听"
fi

if netstat -tulpn 2>/dev/null | grep -q ":443 "; then
    echo "   ✅ 端口443(HTTPS)正在监听"
    netstat -tulpn 2>/dev/null | grep ":443 " | sed 's/^/   /'
else
    echo "   ❌ 端口443(HTTPS)未被监听"
fi

echo ""
# 检查Nginx状态
echo "3. Nginx服务状态:"
if systemctl is-active aa_nginx &>/dev/null; then
    echo "   ✅ Nginx服务正在运行"
    systemctl status aa_nginx --no-pager | grep "Active:" | sed 's/^/   /'
else
    echo "   ❌ Nginx服务未运行"
fi

echo ""
# 检查系统资源
echo "4. 系统资源使用情况:"
echo "   CPU使用率:"
top -bn1 | grep "Cpu(s)" | sed 's/^/   /'
echo "   内存使用情况:"
free -m | head -n 2 | sed 's/^/   /'

echo ""
# 检查日志文件
echo "5. 日志文件状态:"
if [ -f "logs/gunicorn.log" ]; then
    echo "   ✅ Gunicorn日志文件存在"
    echo "   最新日志(最后5行):"
    tail -n 5 logs/gunicorn.log | sed 's/^/   /'
else
    echo "   ❌ Gunicorn日志文件不存在"
fi

echo ""
# 检查应用文件和目录
echo "6. 应用目录检查:"
if [ -d "app/static/uploads" ]; then
    echo "   ✅ 上传目录存在"
    echo "   权限: $(ls -ld app/static/uploads | awk '{print $1,$3,$4}')"
else
    echo "   ❌ 上传目录不存在"
fi

if [ -f "wsgi.py" ]; then
    echo "   ✅ WSGI入口文件存在"
else
    echo "   ❌ WSGI入口文件不存在"
fi

if [ -f "app.py" ]; then
    echo "   ✅ 应用入口文件存在"
else
    echo "   ❌ 应用入口文件不存在"
fi

echo ""
echo "=== 状态检查完成 ==="
echo "如需重启服务: sudo bash start_optimized.sh"
echo "如需停止服务: sudo bash stop_service.sh" 